package fm.yichenet.service.impl;

import fm.dao.HibernateBaseDao;
import fm.dto.NeiyiUser;
import fm.entity.AccountBalance;
import fm.entity.AccountBalanceOperationLog;
import fm.exception.BizException;
import fm.yichenet.service.AccountBalanceService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;

/**
 * Created by CM on 2017/6/29.
 */
@Service
public class AccountBalanceServiceImpl implements AccountBalanceService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountBalanceService.class);
    @Autowired
    HibernateBaseDao baseDao;


    @Override
    public AccountBalance addOrGetBalance(String userId) {
        String hql = "from AccountBalance ab where ab.wxUserId=?";
        AccountBalance ab = (AccountBalance) baseDao.getUnique(hql, userId);
        if (ab == null) {
            createBalance(userId);
        }
        return (AccountBalance) baseDao.getUnique(hql, userId);
    }

    @Override
    public void updateBalance(BigDecimal amount, String userId, String operationRemark) {
        AccountBalance ab = addOrGetBalance(userId);
        if (ab == null) {
            throw new BizException("未找到用户账户信息!");
        }
        if (StringUtils.isEmpty(operationRemark)) {
            throw new BizException("请备注账户操作!");
        }

        if (amount.doubleValue() < 0) {
            throw new BizException("账户余额不足，操作失败！");
        } else {
            AccountBalanceOperationLog log = new AccountBalanceOperationLog();
            log.setAmountBalance(amount);
            log.setContent(operationRemark);
            log.setTime(new Timestamp(System.currentTimeMillis()));
            log.setWxUserId(userId);
            addOperationLog(log);
        }
        ab.setBalance(amount);
        baseDao.update(ab);
    }

    @Override
    public void createBalance(String wxUserId) {
        String hql = "from AccountBalance ab where ab.wxUserId=?";
        AccountBalance ab = (AccountBalance) baseDao.getUnique(hql, wxUserId);
        if (ab == null) {
            AccountBalance accountBalance = new AccountBalance();
            accountBalance.setWxUserId(wxUserId);
            accountBalance.setBalance(new BigDecimal(0.00));
            accountBalance.setLastTime(new Timestamp(System.currentTimeMillis()));
            accountBalance.setVersion(1L);
            baseDao.add(accountBalance);
            LOGGER.info("创建用户账户:{}", wxUserId);
        }
    }

    @Override
    public void addOperationLog(AccountBalanceOperationLog log) {
        if (log == null) {
            throw new BizException("操作日志不能为空！");
        }

        LOGGER.info("操作用户账户:{},金额数量：{}，操作内容：{}", log.getWxUserId(), log.getAmountBalance(), log.getContent());
        baseDao.add(log);
    }
}
